import React, { useState } from "react";
import DurationInput from "./DurationInput";
import DurationItems from "./DurationItems";
import Button from "../../Button";
import { useStyles } from "./style";
import { getDurationTimeRange, getPresetTimeRange } from "../utils";
import { DurationUnitOption, PresetValue, Timestamp } from "../type";

interface Props {
  timeMark?: string | undefined;
  relativeItemsData: string[];
  presetItemsData: PresetValue[];
  handleConfirm: (v: string, timestamp: Timestamp) => void;
  durationUnitOptions: DurationUnitOption[];
}

function RelativeTime({
  timeMark,
  handleConfirm,
  relativeItemsData,
  presetItemsData,
  durationUnitOptions,
}: Props) {
  const classes = useStyles();
  const isTimeRange = timeMark && timeMark?.indexOf("/") > -1;
  const [selectedTimeMark, setSelectedTimeMark] = useState<string | undefined>(
    isTimeRange ? undefined : timeMark
  );

  const confirmData = (selectedTimeMark: string) => {
    const isPreset =
      presetItemsData.findIndex((item) => item === selectedTimeMark) > -1;
    const timestamp = isPreset
      ? getPresetTimeRange(selectedTimeMark)
      : getDurationTimeRange(selectedTimeMark);
    handleConfirm(selectedTimeMark, timestamp);
  };

  const handleClick = () => {
    if (!selectedTimeMark) {
      return;
    }
    confirmData(selectedTimeMark);
  };

  const onRelativeItemClick = (newSelectedTimeMark: string) =>
    confirmData(newSelectedTimeMark);

  const componentProps = {
    selectedTimeMark,
    presetItems: presetItemsData,
  };

  return (
    <>
      <DurationInput
        {...componentProps}
        setSelectedTimeMark={setSelectedTimeMark}
        durationUnitOptions={durationUnitOptions}
      />
      <DurationItems
        {...componentProps}
        relativeItems={relativeItemsData}
        onChange={onRelativeItemClick}
      />
      <div className={classes.buttonContainer}>
        <Button type="blue" onClick={handleClick}>
          确认
        </Button>
      </div>
    </>
  );
}

export default RelativeTime;
